package student.aistar.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import student.aistar.model.bo.Result;
import student.aistar.model.dto.AddressDTO;
import student.aistar.model.dto.CartProductDTO;
import student.aistar.model.dto.ProductInfoDTO;
import student.aistar.model.entity.*;
import student.aistar.service.IIndexService;
import student.aistar.service.IPersonalCenterService;
import student.aistar.service.IUserService;
import student.aistar.service.impl.CartService;
import student.aistar.service.impl.ProductService;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 实现了
 * ①: 购物车的查询,
 * ②: 购物车商品删除,
 * ③: 结算时对购物车的商品数量, 小计价格进行更新,
 * ④: 结算页面对地址用户查询的地址, 以及添加新的地址
 *
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private ProductService productService;


    @Autowired
    private IUserService userService;

    @Autowired
    IIndexService iIndexService;

    @Autowired
    IPersonalCenterService personalCenterService;





    /**
     * 展示购物车的数据
     * @param model
     * @return
     */
    @GetMapping("/shopping_cart")
    public String shoppingCart(Model model, HttpSession session){
        //将查询到的购物车数据和商品数据返回到页面
        User user = (User) session.getAttribute("user");
        List<Cart> carts = cartService.userCart(user.getUserId());
        List<Double> priceList = new ArrayList<>();
        List<Product> products = new ArrayList<>();
        for (int i = 0; i < carts.size(); i++) {
             Product product = productService.findById(carts.get(i).getProductId());
             priceList.add(product.getPrice() * carts.get(i).getNum());
             products.add(product);
        }
        //购物车集合
        model.addAttribute("carts", carts);
        //总价集合
        model.addAttribute("priceList", priceList);
        //产品集合
        model.addAttribute("products", products);
        return "mi/cart/shopping_cart";
    }

    /**
     * 展示购物车的数据
     * @param model
     * @return
     */
    @GetMapping("/asynCart")
    public String asynCart(Model model, HttpSession session){
        //将查询到的购物车数据和商品数据返回到页面
        User user = (User) session.getAttribute("user");
        List<Cart> carts = cartService.userCart(user.getUserId());
        List<Double> priceList = new ArrayList<>();
        List<Product> products = new ArrayList<>();
        for (int i = 0; i < carts.size(); i++) {
            Product product = productService.findById(carts.get(i).getProductId());
            priceList.add(product.getPrice() * carts.get(i).getNum());
            products.add(product);
        }
        //购物车集合
        model.addAttribute("carts", carts);
        //总价集合
        model.addAttribute("priceList", priceList);
        //产品集合
        model.addAttribute("products", products);
        return "mi/asyn_refresh/cart_product";
    }









    @GetMapping("/add_cart")
    public String addCart(HttpSession session, Model model, Integer productId){
        List<Navclass> navClassList = iIndexService.navClassList();
        model.addAttribute("navClassList", navClassList);


        ProductInfoDTO productInfoDTO = productService.productInfo(productId);
        model.addAttribute("productInfoDTO", productInfoDTO);

        User user = (User) session.getAttribute("user");
        if(user != null){
        }
        return "mi/cart/add_cart";
    }

    @GetMapping("/settlement_cart")
    public String settlementCart(){
        return "mi/cart/settlement_cart";
    }

    @GetMapping("/add_success_Tip")
    public String addSuccessTip(Model model){
        List<Navclass> navClassList = iIndexService.navClassList();
        model.addAttribute("navClassList", navClassList);
        return "mi/cart/add_success_Tip";
    }


    /**
     * 根据Id删除购物车的商品
     * @param id
     */
    @PostMapping("/deleteCartProduct")
    public String deleteCartProduct(Integer id){
        cartService.deleteCartProduct(id);
        return "redirect:shopping_cart";
    }


    /**
     * 将前端传过来的产品Id列表和产品的数量Nums封装到一个对象里面
     * @param productIds 封装好的一个对象
     * @return
     */
    @RequestMapping("/goToSettle")
    public String toSettle(HttpSession session,  Model model, String productIds, String Nums, String paraList){
        //将勾选的产品放入到一个集合
        User user = (User) session.getAttribute("user");

        CartProductDTO cartProductDTO = cartService.goToSettle(user.getUserId(), productIds, Nums, paraList);
        List<Product> productList = cartProductDTO.getProductList();
        List<Cart> cartList = cartProductDTO.getCartList();

        int countProducts = cartProductDTO.getCountProducts();
        int totalPrices = cartProductDTO.getTotalPrices().intValue();



        model.addAttribute("productList", productList);
        model.addAttribute("cartList", cartList);
        model.addAttribute("countProducts", countProducts);
        model.addAttribute("totalPrices", totalPrices);
        return "forward:/cart/settlement_cart";
    }

    /**
     * 对输入地址的校验
     * @param address
     * @return
     */
    @PostMapping("/checkAddress")
    @ResponseBody
    public Result del(Address address){
        //手机号正则表达收
        Pattern phoneReg = Pattern.compile("^((13[0-9])|(14[0|5|6|7|9])|(15[0-3])|(15[5-9])|(16[6|7])|(17[2|3|5|6|7|8])|(18[0-9])|(19[1|8|9]))\\d{8}$");
        Matcher m = phoneReg.matcher(address.getUserPhone());

        //字符串
        Pattern lengthReg = Pattern.compile("^.{5,32}$");
        Matcher m2 = lengthReg.matcher(address.getUserAddress());
        if(address.getUserName().equals("")){
//            System.out.println(11);
            return new Result("300", "用户名为空");
        }else if(address.getUserPhone().equals("")){
            return new Result("400", "手机号为空");
        }else if(!m.matches()){
            return new Result("500", "手机号码输入格式有误");
        }
        else if(!m2.matches()){
            return new Result("600", "详细地址长度不对, 最小为5个字, 最大32个字");
        }
        return new Result("200","添加成功");
    }

    /**
     * 抽取出来的地址异步分离页面, 将数据返回到该页面
     * @param session
     * @return
     */
    @GetMapping("/chose_address")
    public String chose_address(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        AddressDTO addressDTO = userService.findAddressById(user.getUserId());


        model.addAttribute("addressList", addressDTO.getAddressList());
        model.addAttribute("addressDetailList", addressDTO.getAddressDetailList());
        return "mi/asyn_refresh/chose_address";
    }


    /**
     * 如果校验的地址正确, 则插入数据到数据库
     * @return
     */
    @PostMapping("/addAddress")
    public String addAddress(Address address){
        userService.addAddress(address);
        return "redirect:chose_address";
    }


    @PostMapping("/reviseAddress")
    @ResponseBody
    public Result reviseAdress(Address address){
        userService.reviseAddress(address);
        return new Result("200", "修改成功");
    }
}
